//
//  CLAddCaseTableViewController.m
//  CareLink
//
//  Created by tanky on 16/8/19.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLAddCaseTableViewController.h"
#import "CLAddCaseTableView.h"
#import "CLTextViewCell.h"
#import "CLImageUpdateTableViewCell.h"
#import "CLSelectDiseaseDetailController.h"
#import "CLSelectDiseaseTypeController.h"
#import "CLSymptomsDesController.h"

@interface CLAddCaseTableViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>


@end

@implementation CLAddCaseTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI{
    self.title = @"添加病例";
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = btnItem;
    CLAddCaseTableView *tv = [[CLAddCaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView = tv;
    self.tableView.backgroundColor = [UIColor colorWithRed:230 green:230 blue:230];
    self.tableView.bounces = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"CLTextViewCell" bundle:nil] forCellReuseIdentifier:@"textView_cellid"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CLImageUpdateTableViewCell" bundle:nil] forCellReuseIdentifier:@"imageUpdate_cellid"];
    self.tableView.estimatedRowHeight = 100;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 1;
            break;
        case 3:
            return 1;
            break;
        default:
            break;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            if (self.diseaseTypeparameter) {
                UITableViewCell *cell = [self defaultCellWithLeftName:@"疾病类型:" andRightName:self.diseaseTypeparameter];
                cell.textLabel.textColor = [UIColor blackColor];
                return cell;
            }else{
            UITableViewCell *cell = [self defaultCellWithLeftName:@"疾病类型:" andRightName:@"请选择"];
                return cell;
            }
        }
        if (indexPath.row == 1) {
            if (self.diseaseDetail) {
                UITableViewCell *cell = [self defaultCellWithLeftName:@"疾病细分:" andRightName:self.diseaseDetail];
                cell.textLabel.textColor = [UIColor blackColor];
                return cell;
            }else{
                UITableViewCell *cell = [self defaultCellWithLeftName:@"疾病细分:" andRightName:@"请选择"];
                return cell;
            }
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            UITableViewCell *cell = [self defaultExCellWithLeftName:@"病症描述:" andRightName:@"添加疾病描述标签 ⊕"];
            return cell;
        }
        if (indexPath.row == 1) {
            CLTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textView_cellid" forIndexPath:indexPath];
            __weak typeof(self) weakSelf = self;
            [cell setSymptomDesBlock:^(NSString *symptomDes) {
                weakSelf.symptomDes = symptomDes;
            }];
            if (self.symptomDes) {
                cell.textString = self.symptomDes;
            }
            cell.placeHolderString = @"请简要描述疾病的症状";
            return cell;
        }
    }else if (indexPath.section == 3){
        if (self.btnName) {
            UITableViewCell *cell = [self buttonCellWithName:self.btnName];
            return cell;
        }else{
            UITableViewCell *cell = [self buttonCellWithName:@"确定"];
            return cell;
        }
    }
    
    CLImageUpdateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageUpdate_cellid" forIndexPath:indexPath];
    if (self.firstImage) {
        [cell.addImageButton setImage:self.firstImage forState:UIControlStateNormal];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak typeof(self) weakSelf = self;
    cell.addPicBlock = ^(UIButton *btn){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;//设置类型为相机
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = weakSelf;//设置代理
                picker.allowsEditing = YES;//设置照片可编辑
                picker.sourceType = sourceType;
                //picker.showsCameraControls = NO;//默认为YES
                //创建叠加层
                UIView *overLayView=[[UIView alloc]initWithFrame:CGRectMake(0, 120, 320, 254)];
                //取景器的背景图片，该图片中间挖掉了一块变成透明，用来显示摄像头获取的图片；
                UIImage *overLayImag=[UIImage imageNamed:@"zhaoxiangdingwei.png"];
                UIImageView *bgImageView=[[UIImageView alloc]initWithImage:overLayImag];
                [overLayView addSubview:bgImageView];
                picker.cameraOverlayView=overLayView;
                picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;//选择前置摄像头或后置摄像头
                [weakSelf presentViewController:picker animated:YES completion:^{
                }];
            }
            else {
                // 声明一个 UILabel 对象
                UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 225, 120, 30)];
                // 设置提示内容
                [tipLabel setText:@"该设备无相机"];
                tipLabel.backgroundColor = [UIColor blackColor];
                tipLabel.layer.cornerRadius = 5;
                tipLabel.layer.masksToBounds = YES;
                tipLabel.textAlignment = NSTextAlignmentCenter;
                tipLabel.textColor = [UIColor whiteColor];
                [weakSelf.tableView addSubview:tipLabel];
                [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(weakSelf.tableView).offset(weakSelf.tableView.bounds.size.height / 5);
                    make.centerX.equalTo(weakSelf.tableView);
                }];
                // 设置时间和动画效果
                [UIView animateWithDuration:2.0 animations:^{
                    tipLabel.alpha = 0.0;
                } completion:^(BOOL finished) {
                    // 动画完毕从父视图移除
                    [tipLabel removeFromSuperview];
                }];
            }
        }
                                    ]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 内容类型
            picker.delegate = weakSelf; // 设置代理
            picker.allowsEditing = YES; // 是否可以编辑
            [weakSelf presentViewController:picker animated:YES completion:nil]; // 跳到相册
        }
                                    ]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [weakSelf presentViewController:alertController animated:YES completion:nil];
        
    }
;
    return cell;

}


- (UITableViewCell *)defaultCellWithLeftName:(NSString *)leftName andRightName:(NSString *)rightName{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"default_cellid"];
    cell.textLabel.text = leftName;
    cell.detailTextLabel.text = rightName;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (UITableViewCell *)defaultExCellWithLeftName:(NSString *)leftName andRightName:(NSString *)rightName{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"defaultEx_cellid"];
    cell.textLabel.text = leftName;
    cell.detailTextLabel.text = rightName;
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0 green:197 blue:197];
    return cell;
}

//点击确定按钮的行为
- (UITableViewCell *)buttonCellWithName:(NSString *)name{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"button_cellid"];
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:name forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor colorWithRed:0 green:197 blue:197];
    btn.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, cell.bounds.size.height);
    [cell addSubview:btn];
    [btn addTarget:self action:@selector(return2PreView) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)return2PreView{

    if (self.updateImages) {
        [self.addCaseData setObject:self.updateImages forKey:@"updateImages"];
    };
    if (self.diseaseTypeparameter && self.diseaseDetail && self.symptomDes) {
 
        [self.addCaseData setObject:self.diseaseTypeparameter forKey:@"diseaseTypeparameter"];
        [self.addCaseData setObject:self.diseaseDetail forKey:@"diseaseDetail"];
        [self.addCaseData setObject:self.symptomDes forKey:@"symptomDes"];
        NSDate *date = [NSDate date];
        
        NSDateFormatter *date_formatter = [[NSDateFormatter alloc]init];
        
        [date_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSString *dateString = [date_formatter stringFromDate:date];
        
        [self.addCaseData setObject:dateString forKey:@"time"];
        
        self.caseBlock(self.addCaseData);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 225, 120, 30)];
        // 设置提示内容
        [tipLabel setText:@"请将信息填写完整"];
        tipLabel.backgroundColor = [UIColor blackColor];
        tipLabel.layer.cornerRadius = 5;
        tipLabel.layer.masksToBounds = YES;
        tipLabel.textAlignment = NSTextAlignmentCenter;
        tipLabel.textColor = [UIColor whiteColor];
        [self.tableView addSubview:tipLabel];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.tableView).offset(self.tableView.bounds.size.height / 5);
            make.centerX.equalTo(self.tableView);
        }];
        // 设置时间和动画效果
        [UIView animateWithDuration:2.0 animations:^{
            tipLabel.alpha = 0.0;
        } completion:^(BOOL finished) {
            // 动画完毕从父视图移除
            [tipLabel removeFromSuperview];
        }];
    };
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                CLSelectDiseaseTypeController *selectDiseaseTypecontroller = [CLSelectDiseaseTypeController new];
                    __weak typeof(self) weakSelf = self;
                [selectDiseaseTypecontroller setDiseaseTypeBlock:^(NSString *diseaseType) {
                    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.detailTextLabel.text = diseaseType;
                    cell.detailTextLabel.textColor = [UIColor blackColor];
                    weakSelf.diseaseTypeparameter = diseaseType;
                }];
                [self showViewController:selectDiseaseTypecontroller sender:nil];
            }else{
                CLSelectDiseaseDetailController *selectDiseaseDetailController = [CLSelectDiseaseDetailController new];
                __weak typeof(self) weakSelf = self;
                selectDiseaseDetailController.diseaseDetailBlock = ^(NSString *diseaseDetail){
                    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.detailTextLabel.text = diseaseDetail;
                    cell.detailTextLabel.textColor = [UIColor blackColor];
                    weakSelf.diseaseDetail = diseaseDetail;
                };
                if (self.diseaseTypeparameter == 0) {
                    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 225, 120, 30)];
                    // 设置提示内容
                    [tipLabel setText:@"请选择疾病类型"];
                    tipLabel.backgroundColor = [UIColor blackColor];
                    tipLabel.layer.cornerRadius = 5;
                    tipLabel.layer.masksToBounds = YES;
                    tipLabel.textAlignment = NSTextAlignmentCenter;
                    tipLabel.textColor = [UIColor whiteColor];
                    [self.tableView addSubview:tipLabel];
                    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerY.equalTo(self.tableView).offset(self.tableView.bounds.size.height / 5);
                        make.centerX.equalTo(self.tableView);
                    }];
                    // 设置时间和动画效果
                    [UIView animateWithDuration:2.0 animations:^{
                        tipLabel.alpha = 0.0;
                    } completion:^(BOOL finished) {
                        // 动画完毕从父视图移除
                        [tipLabel removeFromSuperview];
                    }];
                }else{
                selectDiseaseDetailController.diseaseTypeparameter = self.diseaseTypeparameter;
                [self showViewController:selectDiseaseDetailController sender:nil];
                }
            }
            break;
        case 1:
            if (indexPath.row == 0) {
                CLSymptomsDesController *symptomDesController = [CLSymptomsDesController new];
                [self showViewController:symptomDesController sender:nil];
            }
            break;
        case 2:
            break;
        case 3:
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    // 获取文件类型
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    // 判断是不是图片
    if ([type isEqualToString:@"public.image"]) {
        // 关闭相册
        [picker dismissViewControllerAnimated:YES completion:nil];
        self.firstImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CLImageUpdateTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
        [cell.addImageButton setImage:self.firstImage forState:UIControlStateNormal];
        [self.addCaseData setObject:self.firstImage forKey:@"image"];
    }
}

-(NSMutableDictionary *)addCaseData
{
    if (!_addCaseData) {
        _addCaseData = [[NSMutableDictionary alloc]init];
    }
    return _addCaseData;
    
}

-(void)dealloc
{
    NSLog(@"asjldfjals;");
}

@end
